import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PoemType } from './entities/poem-type.entity';
import { DeepPartial, FindOptionsWhere, Like, Repository } from 'typeorm';
import { CreateDto } from './dto/create.dto';
import { DeleteDto } from './dto/delete.dto';
import { UpdateDto } from './dto/update.dto';
import { FindDto } from './dto/find.dto';
import { FindListDto } from './dto/find-list.dto';
import { scrapePoemType } from 'src/common/utils/scrape/poem-type';

@Injectable()
export class PoemTypeService {
  @InjectRepository(PoemType)
  private readonly poemTypeRepository: Repository<PoemType>;

  async create(createDto: CreateDto) {
    const isExist = await this.poemTypeRepository.findOne({
      where: {
        name: createDto.name,
      },
    });
    if (isExist) {
      throw new BadRequestException('分类名称已存在');
    }
    return await this.poemTypeRepository.save(createDto);
  }

  async delete({ ids }: DeleteDto) {
    if (!ids || ids.length === 0) {
      throw new BadRequestException('参数错误');
    }
    const result = await this.poemTypeRepository.delete(ids);
    if (result.affected === 0) {
      throw new BadRequestException('分类不存在');
    }
    return result;
  }

  async update(updateDto: UpdateDto) {
    const isExist = await this.poemTypeRepository.findOne({
      where: {
        id: updateDto.id,
      },
    });
    if (!isExist) {
      throw new BadRequestException('分类不存在');
    }
    return await this.poemTypeRepository.update(updateDto.id, updateDto);
  }

  async find({ id, name }: FindDto) {
    const where: FindOptionsWhere<PoemType> = {};
    if (id) {
      where.id = id;
    }
    if (name) {
      where.name = Like(`%${name}%`);
    }
    return await this.poemTypeRepository.find({
      where,
      relations: ['poemTags'],
    });
  }

  async list({ page, limit, name, ...restDto }: FindListDto) {
    const query: FindOptionsWhere<Omit<FindListDto, 'page' | 'limit'>> =
      restDto;
    if (name) {
      query.name = Like(`%${name}%`);
    }
    const [list, total] = await this.poemTypeRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
      relations: ['poemTags'],
    });
    return {
      list,
      total,
      page,
      limit,
    };
  }

  // 爬取数据
  async crawl() {
    const res = await scrapePoemType('https://aspoem.com/zh-Hans/tag');
    const result = res.map((item) => this.poemTypeRepository.create(item));
    return await this.poemTypeRepository.save(result as DeepPartial<PoemType>);
  }
}
